/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"

#include "beep_demo.h"
#include "light_demo.h"
#include "infrared_demo.h"

#define TASK_STACK_SIZE 1024
#define TASK_PRIO 25

const unsigned char rgbDutyLow[] = {20,4,20};  //低亮度
const unsigned char rgbDutyHig[] = {99,99,99}; //高亮度

//初始化蜂鸣器相关参数
struct BEEPCTRLATTR gBeepCtrlAttr = {
    .times = 0,
    .duty  = 0.4,
    .period = 500,
    .callTime = 200};

static void MainDemoTask(void)
{
    enum ENV_BODY_STATE  envBodyState = BODY_NOT;   //记录人体状态变量
    enum ENV_LIGHT_STATE envLightState = LIGHT_DAY; //记录环境光照变量   

    //蜂鸣器初始化
    BeepInit();

    //红外传感器初始化
    InfraredSensorInit();

    //三色灯初始化
    TricolorLightInit();

    for(;;)
    {
        //更新当前环境红外人体状态
        envBodyState = GetEnvBodyState();
        printf("envBodyState = %d \r\n",envBodyState);
       
        //有人到来时蜂鸣器响，RGB灯在暗环境下点亮
        if(envBodyState == BODY_COME)
        {
            gBeepCtrlAttr.times = 2;

            //更新当前环境光照状态
            envLightState = GetEnvLightState();
            if(envLightState == LIGHT_DUSK)
            {
                TricolorLightStart(rgbDutyLow[0], rgbDutyLow[1], rgbDutyLow[2]);
            }
            else if(envLightState == LIGHT_NIGHT)
            {
                TricolorLightStart(rgbDutyHig[0], rgbDutyHig[1], rgbDutyHig[2]);  
            }
            else
            {
                TricolorLightStop();
            }
        }

        //有人离开时蜂鸣器响, RGB灯熄灭
        else if(envBodyState == BODY_LEAVE)
        {
            gBeepCtrlAttr.times = 2;
            TricolorLightStop();
        }

        //beep控制函数
        BeepCtrl(&gBeepCtrlAttr); 
 
        usleep(200000);
    }
}

static void MainDemoEntry(void)
{
    osThreadAttr_t attr;
    attr.name = "MainDemoTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)MainDemoTask, NULL, &attr) == NULL)
    {
        printf("[MainDemoExample] Falied to create Main Demo Task!\n");
    }
	return;
}
APP_FEATURE_INIT(MainDemoEntry);

